package com.ctw.tinyservices.id.server.segment.api;

import com.ctw.tinyservices.id.common.dto.ResponseDTO;
import com.ctw.tinyservices.id.common.dto.helper.ResponseDTOHelper;
import com.ctw.tinyservices.id.common.enums.code.ErrorCodeEnum;
import com.ctw.tinyservices.id.server.api.AbstractIdApi;
import com.ctw.tinyservices.id.server.segment.enums.SegmentErrorCodeEnum;
import com.ctw.tinyservices.id.server.segment.handler.IdSegmentHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author TongWei.Chen 2022/3/18 11:27
 *
 * 号段模式api
 **/
@RestController
@RequestMapping("/segment")
public class IdSegmentApi extends AbstractIdApi {

    @Autowired
    private IdSegmentHandler idSegmentHandler;

    @GetMapping("/{bizType}")
    public ResponseDTO<Long> get(@PathVariable String bizType) {
        if (! canVisit(bizType)) {
            return ResponseDTOHelper.fail(ErrorCodeEnum.AUTH_ERROR);
        }
        Long id = idSegmentHandler.getId(bizType);
        return null == id ? ResponseDTOHelper.fail(SegmentErrorCodeEnum.ID_IS_NULL) : ResponseDTOHelper.success(id);
    }

    @GetMapping("/{bizType}/{num}")
    public ResponseDTO<List<Long>> get(@PathVariable("bizType") String bizType, @PathVariable("num") int num) {
        return batchId(bizType, num);
    }

    @Override
    protected List<Long> doBatchId(String bizType, int num) {
        return idSegmentHandler.listId(bizType, num);
    }
}
